package com.example.lncd.ui.auth;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import com.example.lncd.R;
import com.example.lncd.model.User;
import com.example.lncd.ui.RoleSelectionActivity;
import com.example.lncd.ui.elderly.ElderlyMainActivity;
import com.example.lncd.ui.family.FamilyMainActivity;
import com.example.lncd.util.PreferenceManager;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class LoginActivity extends AppCompatActivity {
    
    private ViewPager2 viewPager;
    private TabLayout tabLayout;
    private AuthPagerAdapter pagerAdapter;
    private PreferenceManager preferenceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        // 初始化偏好管理器
        preferenceManager = new PreferenceManager(this);
        
        // 检查用户是否已登录
        if (preferenceManager.isLoggedIn()) {
            // 根据用户类型导航到相应界面
            User.UserType userType = preferenceManager.getUserType();
            if (userType == User.UserType.ELDERLY) {
                navigateToElderlyMain();
            } else if (userType == User.UserType.FAMILY) {
                navigateToFamilyMain();
            } else {
                navigateToRoleSelection();
            }
            finish();
            return;
        }
        
        // 初始化视图
        viewPager = findViewById(R.id.viewPager);
        tabLayout = findViewById(R.id.tabLayout);
        
        // 设置ViewPager适配器
        pagerAdapter = new AuthPagerAdapter(this);
        viewPager.setAdapter(pagerAdapter);
        
        // 关联TabLayout和ViewPager
        new TabLayoutMediator(tabLayout, viewPager,
                (tab, position) -> {
                    if (position == 0) {
                        tab.setText("登录");
                    } else {
                        tab.setText("注册");
                    }
                }).attach();
    }
    
    public void navigateToRoleSelection() {
        Intent intent = new Intent(this, RoleSelectionActivity.class);
        startActivity(intent);
        finish();
    }
    
    public void navigateToRoleSelection(Long userId) {
        Intent intent = new Intent(this, RoleSelectionActivity.class);
        if (userId != null) {
            intent.putExtra("USER_ID", userId);
        }
        startActivity(intent);
        finish();
    }
    
    public void navigateToElderlyMain() {
        Intent intent = new Intent(this, ElderlyMainActivity.class);
        startActivity(intent);
        finish();
    }
    
    public void navigateToFamilyMain() {
        Intent intent = new Intent(this, FamilyMainActivity.class);
        startActivity(intent);
        finish();
    }
} 